package cn.com.cifi.mars.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @Description：门户待办工具
 * @author：yyd
 * @date：2020年6月22日 上午10:22:11
 */
@Slf4j
@Component
public class PortalMqUtils {

	@Value("${portal.activemq.url}")
	private  String brokerUrl;

	/**
	 * 系统编码
	 */
	@Value("${PORTAL_SYSCODE}")
	private String sysCode;
	
	/**
	 * 发起系统
	 */
	@Value("${wait_sys_code}")
	private String startSyscode;
	
	@Value("${PORTAL_SECRET_KEY}")
	private  String secretKey;
	
	@Value("${consumerCount}")
	private int consumerCount;
	
	@Value("${wait_handle_queue}")
	private String waitQueueName;
	
	/**
	 * 发送生产者消息 创建分组
	 * @throws Exception
	 */
	public void start(String instanceId, String msg) {
		try {
			ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(sysCode, secretKey, brokerUrl);
			Connection connection = connectionFactory.createConnection();

			connection.start();
			Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(waitQueueName);
			MessageProducer producer = session.createProducer(destination);
			// 消息的内容
			TextMessage message = session.createTextMessage(msg);
			// 设置分组
			message.setStringProperty("JMSXGroupID", this.generatorCode(instanceId));
			producer.send(message);
			session.commit();
			session.close();
			connection.close();
		} catch (JMSException e) {
			log.error("###### errorMsg: ", e);
		}
	}

	/**
	 * 接收消息
	 * @throws Exception
	 */
	public void receive(String queueName) throws Exception {
		log.info("###### msg: " + queueName);
	}
	
	/**
     * 通过流程流水号与消费者数量(门户决定)生产分组编码
     *
     * @param instanceId
     * @param consumerCount
     * @return
     */
	private String generatorCode(String instanceId) {
        int i = 0;
        for (byte b : instanceId.getBytes()) {
            i += b;
        }
        return "G" + (i % consumerCount + 1);
    }
}